package com.copa.gamestore.module.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.copa.gamestore.module.order.domain.OrderLog;
import com.copa.gamestore.module.order.mapper.OrderLogMapper;
import com.copa.gamestore.module.order.service.OrderLogService;
import com.copa.gamestore.module.order.vo.OrderLogVo;
import com.copa.gamestore.module.user.application.UserApplicationService;
import com.copa.gamestore.module.user.domain.UserAccount;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author copa
 * @createDate 2022-09-29 10:10
 * @function
 */
@Service
public class OrderLogServiceImpl implements OrderLogService {

    @Resource
    private OrderLogMapper orderLogMapper;

    @Resource
    private UserApplicationService userApplicationService;

    @Override
    public void add(OrderLogVo orderLogVo) {
        OrderLog orderLog = new OrderLog();
        BeanUtils.copyProperties(orderLogVo, orderLog);
        UserAccount userAccount = Objects.isNull(orderLogVo.getUserId())
                ? userApplicationService.account().getData()
                : userApplicationService.accountByUserId(orderLogVo.getUserId());
        orderLog.setBeforeAccount(userAccount.getAccount())
                .setAfterAccount(userAccount.getAccount().setScale(2).subtract(orderLogVo.getMoney().setScale(2)))
                .setUserId(userAccount.getUserId());
        if (orderLogMapper.insert(orderLog) <= 0) {
            throw new RuntimeException();
        }
    }

    @Override
    public List<OrderLog> get(Long userId, String orderSn) {
        QueryWrapper<OrderLog> wrapper = new QueryWrapper<OrderLog>();
        if (Objects.nonNull(userId)) {
            wrapper.eq("user_id", userId);
        }
        if (Objects.nonNull(orderSn)) {
            wrapper.eq("order_sn", orderSn);
        }
        return orderLogMapper.selectList(wrapper);
    }
}
